<script setup lang="ts">
import {useProjectStore} from "@/stores/projectStore.ts";
import {useRouter} from 'vue-router';
import { ref } from 'vue';
import { createProject } from '../../api/project/project';



const projectStore = useProjectStore()
const router = useRouter()

const isModalVisible = ref(false); // 控制模态框的显示和隐藏
const newProjectName = ref('');  // 绑定输入框中的项目名称

function onProjectChanged() {
  if (projectStore.projectId) {
    router.push({name: 'languages', params: {projectId: projectStore.projectId}})
  }
}

function showModal() {
  isModalVisible.value = true;
}

function handleCancel() {
  isModalVisible.value = false;
  newProjectName.value = '';
}

async function handleOk() {
  if (newProjectName.value.trim()) {
    try {
      const newProject = await createProject(newProjectName.value);
        if (newProject==true) {
                alert('新建项目成功:'+newProjectName.value);
                isModalVisible.value = false;
                newProjectName.value = '';
        }
    } catch (error) {
      console.error('创建项目失败:');
      alert('创建项目失败，请重试');
    }
  } else {
    alert('项目名称不能为空');
  }
}

</script>
<template>
  <div class="w-[70vw] h-[300px] bg-white">
    <div class="h-full flex justify-center items-center">
      <div class="flex justify-center items-center gap-4 text-[1.1rem]">
        <div class="flex">
          <div>进入项目aa：</div>
          <a-select v-model:value="projectStore.projectId" class="w-40" @change="onProjectChanged"
                    placeholder="选择一个项目"
                    show-search>
            <a-select-option v-for="project in projectStore.projects" :key="project.projectId"
                             :value="project.projectId"
            >
              {{ project.projectName }}
            </a-select-option>
          </a-select>
        </div>
        <div>
          或
        </div>
        <div>
          <a-button type="primary" @click="showModal">新建项目</a-button>
        </div>
      </div>
    </div>

     <!-- 新建项目弹框 -->
     <a-modal v-model:visible="isModalVisible" title="新建项目" @ok="handleOk" @cancel="handleCancel">
      <a-form layout="vertical">
        <a-form-item label="项目名称">
          <a-input v-model:value="newProjectName" placeholder="请输入项目名称" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
      </template>
    </a-modal>

  </div>
</template>
